package leetcode;

import java.util.Stack;

public class l0150_逆波兰表达式求值 {

    private boolean isOperator(String token){
        return "+-*/".contains(token);
    }

    private int calculate(Integer left,Integer right,String operator){
        switch (operator){
            case "+": return left+right;
            case "-": return left-right;
            case "*": return left*right;
            case "/": return left/right;
            default: return 0;
        }
    }

    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<>();
        for (String token : tokens) {
            if (isOperator(token)){
                Integer right = stack.pop();
                Integer left = stack.pop();
                int result = calculate(left, right, token);
                stack.push(result);
            }else{
                stack.push(Integer.valueOf(token));
            }
        }
        return stack.pop();
    }
}
